<template>
  <div
    @click="speakText"
    @scroll="onScroll"
    class="breeze__pdf"
    :style="{ width: props.width }"
  >
    <div
      ref="pdfContainer"
      :class="[props.width == 'default' ? '' : 'pdf-auto-size']"
    ></div>
  </div>
</template>
<script setup>
import { ref, watch, onMounted, defineProps } from 'vue'
import * as PDFJS from 'pdfjs-dist'
import pdfRender from './js/useRenderEle'
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/legacy/build/pdf.worker.entry.js')
// TODO：下个版本涂鸦工具库fabric
const props = defineProps({
  // pdf文件地址
  src: {
    type: String,
    default: 'http://192.168.0.118:3000/test1.pdf'
  },
  // 底部触发新渲染距离
  distance: {
    type: Number,
    default: 1000
  },
  // TODO：缩放比例(版本0.1没有修改的必要)
  scale: {
    type: Number,
    default: 1
  },
  // 模糊程度(模糊度越高首次加载时间越短)
  blur: {
    type: Number,
    default: 10
  },
  // 单次渲染页数(渲染页数越少速度越快，如果要实现上拉加载,请确保页面超过可视范围) // TODO：修复必须超过可视区域bug
  renderSIze: {
    type: Number,
    default: 99
  },
  // TODO：0.2版本预留翻页参数
  // triggerPage: {
  //   type: Number,
  //   default: 1
  // },
  // TODO：显示模式0.2版本会新增横向渲染模式
  module: {
    type: String,
    default: 'vertical'
  },
  // pdf所占用的宽度
  width: {
    type: String,
    default: 'auto'
  },
  // pdf旋转角度
  rotation: {
    type: Number,
    default: 0
  },
  // 是否开启单机页面语音播报 // TODO:更改为滑动关闭控制，且从当前页面可视区域开头进行播报
  speak: {
    type: Boolean,
    default: true
  }
})
const _pdfRender = ref({})
const pdfContainer = ref(null)
const currentPage = ref(1)
const totalPage = ref(0)
onMounted(async () => {
  try {
    speakCheck()
    await pdfFailGet()
    renderSIzesThrottled()
  } catch (error) {
    handleError(error)
  }
})
async function renderSIzesThrottled() {
  const delay = 10
  const endNumPages =
    currentPage.value + props.renderSIze < totalPage.value
      ? currentPage.value + props.renderSIze
      : totalPage.value
  for (
    currentPage.value;
    currentPage.value <= endNumPages;
    currentPage.value++
  ) {
    if (currentPage.value > 1) {
      await new Promise((resolve) => setTimeout(resolve, delay)) // 延迟一段时间
    }
    const canvasBlur = await _pdfRender.value.renderPdfPage(currentPage.value)
    pdfContainer.value.appendChild(canvasBlur)
  }
}
function onScroll(event) {
  const { scrollHeight, scrollTop, clientHeight } = event.target
  const isNearBottom =
    scrollHeight - (scrollTop + clientHeight) <= props.distance
  if (!isNearBottom) return
  if (props.module == 'vertical') {
    renderSIzesThrottled()
  }
}
function speakCheck() {
  if (props.speak) {
    const script = document.createElement('script')
    script.src =
      'https://code.responsivevoice.org/responsivevoice.js?key=bYrFnecu'
    window.document.body.appendChild(script)
  }
}
async function pdfFailGet() {
  const pdfDoc = await PDFJS.getDocument(props.src).promise
  _pdfRender.value = pdfRender(pdfDoc, props)
  totalPage.value = pdfDoc.numPages
}
function handleError(error) {
  console.error('错误:', error)
}
function resetPdf() {
  pdfContainer.value.innerHtml = ''
}
watch(
  function () {
    return props.rotation
  },
  () => {
    resetPdf()
    if (props.module == 'vertical') {
      renderSIzesThrottled()
    }
  }
)
</script>

<style scoped>
@import './style/index.css';
</style>

<!-- <template>
  <div id="editor">
    <mavon-editor
      v-model="fileContent"
      style="height: 100%"
      :toolbars="toolbars"
      @save="saveInfo"
    ></mavon-editor>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from 'vue'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import TurndownService from 'turndown'
import marked from 'marked'
const turndownService = new TurndownService()
const props = defineProps({
  src: {
    type: String,
    default: 'http://10.10.10.136:3000/index.html'
  }
})
const fileContent = ref('')
onMounted(() => {
  fetch(props.src)
    .then((response) => {
      if (response.ok) {
        return response.text()
      } else {
        throw new Error('请求失败')
      }
    })
    .then((data) => {
      const markdown = turndownService.turndown(data)
      fileContent.value = markdown
    })
    .catch((error) => {
      console.error(error)
    })
})
function saveInfo(md, html) {
  console.log('这就是html', html)
}
const toolbars = {
  bold: true, // 粗体
  italic: true, // 斜体
  header: true, // 标题
  underline: true, // 下划线
  strikethrough: true, // 中划线
  mark: true, // 标记
  superscript: true, // 上角标
  subscript: true, // 下角标
  quote: true, // 引用
  ol: true, // 有序列表
  ul: true, // 无序列表
  link: true, // 链接
  imagelink: true, // 图片链接
  // code: true, // code
  table: true, // 表格
  fullscreen: true, // 全屏编辑
  readmodel: true, // 沉浸式阅读
  // htmlcode: true, // 展示html源码
  help: true, // 帮助
  /* 1.3.5 */
  undo: true, // 上一步
  redo: true, // 下一步
  trash: true, // 清空
  save: true, // 保存（触发events中的save事件）
  /* 1.4.2 */
  navigation: true, // 导航目录
  /* 2.1.8 */
  alignleft: true, // 左对齐
  aligncenter: true, // 居中
  alignright: true, // 右对齐
  /* 2.2.1 */
  subfield: true, // 单双栏模式
  preview: true // 预览
}
</script>

<style>
#editor {
  margin: auto;
  width: 80%;
  height: 580px;
}
</style> -->
